/** 
 * Copyright 2010 Erlacher Felix, Estgfaeller Wolfgang, Ferula Patrick
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package at.socialconference.app;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import at.socialconference.Controller;
import at.socialconference.app.connection.ConnectionHandler;
import at.socialconference.app.model.AConference;
import at.socialconference.app.model.ATalk;
import at.socialconference.app.model.AUser;
import at.socialconference.app.uihelper.AlertHelper;
import at.socialconference.inter.model.Conference;
import at.socialconference.inter.model.Talk;
import at.socialconference.inter.model.User;

public class MenuActivity extends Activity implements OnClickListener {
	private Button conferenceBtn;
	private Button qrBtn;
	private Button contactsBtn;
	private TextView currentConfView;

	private AConference nowCon;
	private Object o;
	private boolean isFirstStart = true;

	private static final int ID_DIALOG_QRCODE = 0;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainmenu);

		conferenceBtn = (Button) findViewById(R.id.mm_conference);
		qrBtn = (Button) findViewById(R.id.mm_qrcode);
		contactsBtn = (Button) findViewById(R.id.mm_contacts);
		currentConfView = (TextView) findViewById(R.id.mm_conferencenow);

		conferenceBtn.setOnClickListener(this);
		qrBtn.setOnClickListener(this);
		contactsBtn.setOnClickListener(this);

		init();

	}

	/**
	 * Initialize App
	 */
	private void init() {
		if (isFirstStart) {
			AUser u = ConnectionHandler.getUser();
			if (u == null) {
				AlertHelper.alert("Failure",
						"Please check Internet Connection", false, this);
			} else {
				Controller.setUser(u);
				setCurrentConference();
				isFirstStart = false;
			}
		}
	}

	/**
	 * Sets the current Conference
	 */
	private void setCurrentConference() {
		Thread t = new Thread() {
			public void run() {
				Conference conf = ConnectionHandler.getCurrentConference();
				if (conf != null) {
					nowCon = new AConference(conf);
				}
			}
		};
		t.start();
		try {
			t.join();
			if (nowCon != null) {
				String tmp = "Current Conference:\n";
				tmp += nowCon.getName();
				tmp += nowCon.getPlace() != null ? "\n@"
						+ nowCon.getPlace().getName() : "";
						currentConfView.setText(tmp);
			} else {
				currentConfView.setText("No Conference at this time");
				conferenceBtn.setVisibility(View.GONE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// For Result of Barcode Reader
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == 0) {
			if (resultCode == RESULT_OK) {
				String contents = intent.getStringExtra("SCAN_RESULT");

				handleQRCode(contents);
			}
		}
	}

	/**
	 * Handles QR Code Result
	 * 
	 * @param contents
	 *            content of result
	 */
	public void handleQRCode(final String contents) {
		showDialog(ID_DIALOG_QRCODE);
		Thread t = new Thread() {
			public void run() {
				o = ConnectionHandler.handleQRCode(contents);
				dismissDialog(ID_DIALOG_QRCODE);
			}
		};

		t.start();
		try {
			t.join();

			if (o instanceof User) {
				Bundle b = new Bundle();
				AUser u = new AUser((User) o);
				b.putParcelable("person", u);
				Intent i = new Intent(this, PeopleActivity.class);
				i.putExtras(b);
				startActivity(i);
			} else if (o instanceof Conference) {
				Bundle b = new Bundle();
				AConference u = new AConference((Conference) o);
				b.putParcelable("conference", u);
				Intent i = new Intent(this, ConferenceTabActivity.class);
				i.putExtras(b);
				startActivity(i);
			} else if (o instanceof Talk) {
				Bundle b = new Bundle();
				ATalk u = new ATalk((Talk) o);
				b.putParcelable("talk", u);
				Intent i = new Intent(this, TalkTabActivity.class);
				i.putExtras(b);
				startActivity(i);
			}

		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}

	protected Dialog onCreateDialog(int id) {
		if (id == ID_DIALOG_QRCODE) {
			ProgressDialog loadingDialog = new ProgressDialog(this);
			loadingDialog.setTitle("Please wait");
			loadingDialog.setMessage("Processing QR Code in");
			loadingDialog.setIndeterminate(true);
			loadingDialog.setCancelable(true);
			return loadingDialog;
		}
		return super.onCreateDialog(id);
	}

	@Override
	public void onClick(View v) {
		if (v.equals(conferenceBtn)) {
			if (nowCon != null) {
				Bundle b = new Bundle();
				b.putParcelable("conference", nowCon);
				Intent i = new Intent(this, ConferenceTabActivity.class);
				i.putExtras(b);
				startActivity(i);
			}
		} else if (v.equals(qrBtn)) {
			createQRDialog();
		} else if (v.equals(contactsBtn)) {
			Bundle b = new Bundle();
			b.putParcelable("person", Controller.getUser());
			Intent i = new Intent(this, PeopleList.class);
			i.putExtras(b);
			startActivity(i);
		}

	}

	private void createQRDialog() {
		Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("QRCode");
		builder.setNeutralButton("My QR-Code",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(
						"com.google.zxing.client.android.ENCODE");
				intent.putExtra("ENCODE_TYPE", "TEXT_TYPE");
				String data = "001#0000" + Controller.getUser().getId();

				intent.putExtra("ENCODE_DATA", data);
				try {
					startActivity(intent);
				} catch (ActivityNotFoundException e) {
					showZxingAlert();
				}
			}
		});
		builder.setPositiveButton("Scan QR-Code",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent(
						"com.google.zxing.client.android.SCAN");
				intent.addCategory(Intent.CATEGORY_DEFAULT);
				try {
					startActivityForResult(intent, 0);
				} catch (ActivityNotFoundException e) {
					showZxingAlert();
				}
			}
		});

		builder.show();
	}

	private void showZxingAlert(){
		AlertDialog alertDialog = new AlertDialog.Builder(this).create();

		alertDialog.setTitle("Activity not found");

		alertDialog.setMessage("Please install \"Xing Barcode Reader from Android Market\"");
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Intent itn = new Intent (Intent.ACTION_VIEW);
				itn.setData (Uri.parse ("market://details?id=com.google.zxing.client.android"));
				itn.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(itn);
			}
		});
		alertDialog.show();
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.mainmenu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mm_mTwitterSettings:

			Intent i = new Intent(this, TwitterSettingsActivity.class);
			startActivity(i);

			return true;
		case R.id.mm_mServerSettings:

			Intent it = new Intent(this, ServerSettings.class);
			startActivity(it);

			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

}
